package ribbitmq_2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

//ribbitmq消费者接受消息
public class Consumer_2 {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        ConnectionFactory c = new ConnectionFactory();
        c.setHost("192.168.64.140");
        c.setPort(5672);
        c.setUsername("admin");
        c.setPassword("admin");
        Connection ch = c.newConnection();
        Channel cha = ch.createChannel();
        //定义队列(谁先启动谁来创建队列)


        cha.queueDeclare("task_queue",
                        true,
                        false,
                        false,
                        null);


        //创建回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                byte[] bytes = delivery.getBody();
                String msg = new String(bytes);
                System.out.println("以收到消息" + msg);
                //判断是否有.有就暂停1s
                for (int i=0;i<msg.length();i++){
                    if(msg.charAt(i) == '.'){
                        try {
                            Thread.sleep(2000);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
                //delivery.getEnvelope().getDeliveryTag() 向服务器发送回执
                cha.basicAck(delivery.getEnvelope().getDeliveryTag(), false);//返回回执信息
                System.out.println("消息处理结束" + msg);
            }
        };

        //取消回调对象
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        //设置消费抓取数
        cha.basicQos(1);//每次只抓取1条

        //消费接受消息,设置第二个参数true(自动ack)  false表示手动确定ack手动回执
        cha.basicConsume("task_queue", false, deliverCallback, cancelCallback);

    }
}
